package sk.naive.talker.tcpadapter;

import sk.naive.talker.adapter.*;

import java.util.*;

/**
 * TableTagProcessor.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.12 $ $Date: 2005/01/11 23:22:37 $
 */
public class TableTagProcessor implements TagProcessor {
	public String process(MessageProcessingContext ctx, String params) throws TagProcessorException {
		TCPUser user = (TCPUser) ctx.getUser();
		List<String> items = ((ItemTagProcessor.ItemConsumer) ctx.getConsumer()).items();

		StringBuilder buffer = new StringBuilder(ctx.getConsumer().result());
		ctx.switchConsumer(new MessageProcessingContext.BufferMessageConsumer(), false);

		String[] tableWidths = params.split(",", -1);
		int cols = tableWidths.length;

		int[] sizes = new int[items.size()];
		int[] sizeArray = new int[cols];

		int col = 0;
		for (String item : items) {
			item = user.sendReplace(item);
			items.set(col, item);
			int size = AnsiUtils.length(item);
			if (sizeArray[col % cols] < size) {
				sizeArray[col % cols] = size;
			}
			sizes[col] = size;
			col++;
		}

		int sizeArraySum = 0;
		for (Integer size : sizeArray) {
			sizeArraySum += size;
		}
		// tu uz mam spravne velkosti stlpcov hadam

		int termCols = user.getCols();

		if (sizeArraySum + cols - 1 <= termCols) {
			col = 0;
			int itemIndex = 0;
			for (String item : items) {
				if (col >= cols) {
					buffer.append(TCPUser.TCP_BR);
					col = 0;
				}
				if (col > 0) {
					buffer.append(" ");
				}
				buffer.append(user.ansiReset()).append(item);
				for (int i = 0; i < sizeArray[col] - sizes[itemIndex]; i++) {
					buffer.append(" ");
				}
				col++;
				itemIndex++;
			}
		} else {
			int tableWidthSum = 0;
			int tableWidthUnspecifiedCount = 0;

			for (String width : tableWidths) {
				if (width.equals("*")) {
					tableWidthUnspecifiedCount++;
				} else {
					tableWidthSum += Integer.valueOf(width);
				}
			}

			if (tableWidthUnspecifiedCount <= 1 && tableWidthSum <= termCols) {
				// data presahuju obrazovku - je nutnych (asi niekde) viac riadkov
				// ale mame zadane pevne sirky.. hadam sa podla nich da riadit
				// todo TCPsimpleTableFormatter(items,tableWidths,sizes,sizeArray)
				// toto je povodny "append" formatovac
				col = 0;
				for (String item : items) {
					if (++col > cols) {
						buffer.append(TCPUser.TCP_BR);
						col = 1;
					}
					if (col > 1) {
						buffer.append(" ");
					}
					buffer.append(user.ansiReset()).append(item);
				}
			} else {
				// todo premakany inteligentny formatovac
				// toto je povodny "append" formatovac
				col = 0;
				for (String item : items) {
					if (++col > cols) {
						buffer.append(TCPUser.TCP_BR);
						col = 1;
					}
					if (col > 1) {
						buffer.append(" ");
					}
					buffer.append(user.ansiReset()).append(item);
				}
			}
		}
		return buffer.append(user.ansiReset()).append(TCPUser.TCP_BR).toString();
	}
}

